package org.elephas.webapp.frontend.resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.wicket.RequestCycle;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.protocol.http.RequestUtils;
import org.elephas.model.Blog;
import org.elephas.model.Post;
import org.elephas.webapp.frontend.page.blog.BlogFrontPage;
import org.elephas.webapp.frontend.page.blog.BlogPostPage;
import org.elephas.webapp.model.DetachableBlogModel;

import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;

public class BlogFeedResource extends FeedResource {

	private static final long serialVersionUID = 1L;

	private DetachableBlogModel blogModel;

	public BlogFeedResource(DetachableBlogModel blogModel) {
		InjectorHolder.getInjector().inject(this);
		this.blogModel = blogModel;
	}

	@Override
	protected SyndFeed getFeed() {
		Blog blog = blogModel.getObject();
		SyndFeed feed = new SyndFeedImpl();
		feed.setFeedType("rss_2.0");
		feed.setTitle(blog.getName());
		feed.setLink(RequestUtils.toAbsolutePath(RequestCycle.get().urlFor(
				BlogFrontPage.class,
				BlogFrontPage.constructPageParameters(blog)).toString()));
		feed.setPublishedDate(blog.getCreated());
		feed.setDescription(blog.getDescription());

		List<SyndEntry> entries = new ArrayList<SyndEntry>();
		List<Post> posts = blogModel.getObject().getRecentPosts(
				Integer.MAX_VALUE);

		for (Post post : posts) {
			SyndEntry entry = new SyndEntryImpl();
			entry.setTitle(post.getTitle());
			entry.setLink(RequestUtils.toAbsolutePath(RequestCycle.get()
					.urlFor(BlogPostPage.class,
							BlogPostPage.constructPageParameters(post))
					.toString()));
			entry.setPublishedDate(post.getCreated());
			entry.setAuthor(post.getUser().getFullName());
			if (post.getUpdated() != null) {
				entry.setUpdatedDate(post.getUpdated());
			}

			SyndContent description = new SyndContentImpl();
			description.setType("text/html");
			description.setValue(post.getContent());

			entry.setDescription(description);
			entries.add(entry);
		}

		feed.setEntries(entries);
		return feed;
	}

	@Override
	protected Date getLastModified() {
		List<Post> posts = blogModel.getObject().getRecentPosts(1);
		if (posts.isEmpty()) {
			return new Date(0);
		}

		return posts.get(0).getCreated();
	}

}
